﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MessagingMediator
{
    public class Consumer
    {
        MessageQueue _channel;
        MessageQueue _redirectChannel;

        public Consumer(MessageQueue channel, MessageQueue redirectChannel)
        {
            _channel = channel;
            _redirectChannel = redirectChannel;

            _channel.ReceiveCompleted += new ReceiveCompletedEventHandler(channel_ReceiveCompleted);
            _channel.BeginReceive();
        }

        private void channel_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            Console.WriteLine("Received message from " + _channel.QueueName);
            MessageQueue mq = (MessageQueue)sender;
            Message message = mq.EndReceive(e.AsyncResult);
            message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });

            Console.WriteLine("Redirecting message to the " + _redirectChannel.QueueName + " queue.");

            _redirectChannel.Send(message);
            Console.WriteLine("Message has been sent.");

            mq.BeginReceive();
        }
    }
}
